import { ref, onMounted, reactive, watch, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { phone, setProvince } from '../../../../utils/validate'
import { useRoute, useRouter } from 'vue-router'
import { useTagsViewStore } from '../../../../store/modules/tagsView'
import {
  outStoreTypePageSelect,
  storeEmpAddressPageSelect,
  storePageSelect,
  rejectOutbound,
  getOutStoreReceiptsUser,
  getOutboundDetail,
  getOutboundMaterial,
  storePositionPageSelect,
  getGoodsStock,
  getInStoreCodeList,
  getInOrOutStoreGoods,
  saveOrCheck,
} from '../../../../api/store'
import { typePageSelect, brandPageSelect } from '../../../../api/goodsInfo'
import { useSettingStore } from '../../../../store/modules/setting'
import { ElTable } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { SnCode, WarehouseOptions } from './types'
import _ from 'lodash'
export default function () {
  /**
   * 激活的路由对象
   */
  const route = useRoute()

  /**
   * 全局路由对象
   */
  const router = useRouter()

  /**
   * 设备列表
   */
  const commoditys = ref([])

  /**
   * 选择序列号弹窗的显示状态
   */
  const selectSnCodeDialogVisible = ref(false)

  /**
   * 当前操作的设备
   */
  const currentOperateCommodity = ref(null)

  /**
   * 审核之前，保存之后的序列号，用于在选择新的序列号再清空后将保存的序列号填充上去
   */
  const snCodeBeforeAudit = ref([])

  /**
   * 显示选择序列号弹窗
   * @param row 设备
   * @param index 设备索引
   */
  const handleShowSelectSnCodeDialog = (row, index: number) => {
    currentOperateCommodity.value = { ...row, index }
    stockCodeVosTemp.value = commoditys.value[currentOperateCommodity.value.index].stockCodeVosTemp
    selectSnCodeDialogVisible.value = true
    nextTick(() => {
      getInStoreCodeListData()
    })
  }

  /**
   * 保存或审核之前的校验
   * @returns {boolean} - true 通过，false 不通过
   */
  const submitVerify = () => {
    let result = true
    if (commoditys.value.length <= 0) {
      ElMessageBox({
        message: '请添加设备',
        type: 'warning',
        title: '提示',
      })
      result = false
      return
    }
    for (let i = 0; i < commoditys.value.length; i++) {
      if (!commoditys.value[i].storeId) {
        ElMessageBox({
          message: '请选择仓库',
          type: 'warning',
          title: '提示',
        })
        result = false
        return
      }

      if (
        !faultsStorePositionFun2(commoditys.value[i].storeId) &&
        !commoditys.value[i].storePositionId
      ) {
        ElMessageBox({
          message: '请选择仓位',
          type: 'warning',
          title: '提示',
        })
        result = false
        return
      }

      if (commoditys.value[i].stockCodeVos.length <= 0) {
        ElMessageBox({
          message: '请选择序列号',
          type: 'warning',
          title: '提示',
        })
        result = false
        return
      }
    }
    return result
  }

  /**
   * 选择序列号确认按钮点击事件
   */
  const onConfirmSnCode = () => {
    if (
      currentOperateCommodity.value.qty <
      commoditys.value[currentOperateCommodity.value.index].stockCodeVosTemp.length
    ) {
      ElMessageBox({
        title: '提示',
        message: '录入序列号数量不能超过出库序列号总数',
        type: 'error',
      })
      return
    }
    commoditys.value[currentOperateCommodity.value.index].stockCodeVos = []
    commoditys.value[currentOperateCommodity.value.index].stockCodeVosTemp.forEach((codeObj) => {
      commoditys.value[currentOperateCommodity.value.index].stockCodeVos.push({
        code: codeObj.code,
      })
    })
    selectSnCodeDialogVisible.value = false
  }

  /**
   * 序列号选择事件
   * @param snCodes - 选择的序列号
   */
  const handleSnCodeSelectionChange = (snCodes: Array<SnCode>) => {
    commoditys.value[currentOperateCommodity.value.index].stockCodeVosTemp = _.cloneDeep(
      snCodeBeforeAudit.value[currentOperateCommodity.value.index],
    )
    if (snCodes.length > 0) {
      commoditys.value[currentOperateCommodity.value.index].stockCodeVosTemp = _.cloneDeep(snCodes)
    }
  }

  const loading = ref(false)
  const total = ref(0)
  const tableDataList = ref(null)
  const pagination = ref()
  const typeLoading = ref(false)
  const storeListRef = ref()
  const TagsViewStore = useTagsViewStore()
  const addrsDom = ref()
  const addrsObj = ref({
    // 地址
    province: '',
    city: '',
    area: '',
    town: '',
  })
  // 刷新页面
  const SettingStore = useSettingStore()
  const refresh = () => {
    SettingStore.setReload()
  }
  // 地址
  function addressValChange() {
    addrsObj.value = addrsDom.value.getSelectAddr()
    newOutForm.value.receiptVo.receiptProvince = addrsObj.value.province
    newOutForm.value.receiptVo.receiptCity = addrsObj.value.city
    newOutForm.value.receiptVo.receiptArea = addrsObj.value.area
    newOutForm.value.receiptVo.receiptTown = addrsObj.value.town
  }
  // 日期类型
  const dateType = ref([
    { title: '时间区间', value: 1 },
    { title: '今天', value: 2 },
    { title: '本周', value: 3 },
    { title: '本月', value: 4 },
    { title: '过去三个月', value: 5 },
  ])
  // 单据来源
  const source = ref([
    { title: '系统单', value: 1 },
    { title: '工单', value: 2 },
    { title: 'ERP单据', value: 3 },
    { title: '仓库移动端单据', value: 4 },
    { title: '第三方系统单据', value: 5 },
    { title: '部门移动端单据', value: 7 }
  ])
  // 出库单状态
  const status = ref([
    { title: '待审核', value: 1 },
    { title: '待出库', value: 2 },
    { title: '驳回', value: 3 },
    { title: '已出库', value: 4 },
    { title: '已作废/取消', value: 5 },
  ])
  // 出库仓类型
  const storeType = ref([
    { title: '内部仓库', value: 0 },
    { title: '部门-外部仓库', value: 1 },
    { title: '工程师-外部仓库', value: 2 },
  ])
  // 收货地址类
  const receiptAddrType = ref([
    { title: '公司', value: 1 },
    { title: '部门仓库', value: 2 },
    { title: '工程师仓库', value: 3 },
  ])
  const newOutForm = ref({
    createTime:
      new Date(Date.now()).toISOString().split('T')[0] +
      ' ' +
      new Date(Date.now()).toTimeString().split(' ')[0], //单据日期
    estimateTime: '', //	预计出库时间
    id: null, //
    delOutBoundMaterialIds: [], //删除的出库物料ID集合
    outboundNo: '',
    outBoundMaterialVos: [
      // {
      //     "goodsId": null,//物料ID
      //     "goodsSpecId": null,//物料规格ID
      //     "id": null,//
      //     "price": 0,//物料单价
      //     "qty": 1,//物料出/入库数量,示例1
      //     "remark": "",//物料出/入库备注
      //     "stockCodeVos": [
      //         {
      //             "code": ""//序列号
      //         }
      //     ],
      //     "storeId": null,//仓库ID
      //     "storePositionId": null,//仓库仓位ID，当仓库启用仓位时，此字段必传
      //     "type": 1//	物料类型：1-成品 ，2-备件
      // }
    ],
    receiptVo: {
      receiptAddrType: 1, //收货地址类型：1-公司，2-部门仓库，3-工程师仓库,示例值(1)

      receiptAddress: '', //
      receiptArea: '', //
      receiptCity: '', //

      receiptName: '', //收货人姓名
      receiptPhone: '', //

      receiptProvince: '', //
      receiptTown: '', //

      relationId: null, //用户表ID/仓库ID
      storePositionId: null, //仓库仓位ID，当仓库启用仓位时生效
    },
    remark: '', //备注
    reviewRemark: '', //	审核备注
    source: 1, //单据来源：1-系统单，2-工单，3-ERP单据，4-仓库移动端单据，5-第三方系统单据,示例值(1)
    storeType: 0, //仓库类型：0-内部仓库，1-部门-外部仓库，2-工程师-外部仓库
    typeId: null, //出库类型ID
  })
  const rulesOutStore = reactive({
    typeId: [{ required: true, message: '出库类型', trigger: ['blur', 'change'] }],
    receiptVo: {
      receiptAddrType: [{ required: true, message: '出库类型', trigger: ['blur', 'change'] }],
      receiptName: [{ required: true, message: '收货人姓名', trigger: 'blur' }],
      receiptPhone: [
        { required: true, message: '收货人手机号', trigger: 'blur' },
        { validator: phone(newOutForm.value.receiptVo.receiptPhone), trigger: 'blur' },
      ],
      receiptAddress: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
      receiptProvince: [
        {
          required: true,
          validator: setProvince(newOutForm.value.receiptVo.receiptProvince),
          trigger: ['blur', 'change'],
        },
      ],
      storePositionId: [{ required: true, message: '仓库仓位', trigger: ['blur', 'change'] }],
    },
    storeType: [{ required: true, message: '仓库类型', trigger: ['blur', 'change'] }],
  })
  // 获取出库下拉类型
  const outStoreType = ref([])
  const outStoreTypeValue = ref()
  const getoutStoreTypePageSelect = async (val) => {
    const data = {
      limit: 0,
      name: val,
      page: 0,
    }
    typeLoading.value = true
    await outStoreTypePageSelect(data).then((res) => {
      if (res) {
        if (res.data.code == 20000) {
          outStoreType.value = res.data.data.rows
        }
      }
    })
    typeLoading.value = false
  }
  const changeOutType = (val) => {
    outStoreTypeValue.value = val
  }

  //仓库及人员地址下拉列表查询
  const valuestoreEmpAddress = ref()
  const inputValueSch = (val) => {
    valuestoreEmpAddress.value = val
  }
  // 出库仓类型变化
  const storeTypeChange = () => {
    commoditys.value = commoditys.value.map((o) => {
      o.storeId = null
      o.storePositionId = null
      o.storePositionList = []
      o.systemStock = null
      o.stockCodeVos = []
      o.stockCodeVosTemp = []
      return o
    })
    getstorePageSelect('')
  }
  const modules = ref([])
  const loadingEmp = ref(false)
  // 获取仓库人员及地址下拉
  async function getstoreEmpAddressPageSelect(val) {
    loadingEmp.value = true
    const data = {
      limit: 0,
      name: val,
      page: 0,
    }
    if (newOutForm.value.receiptVo.receiptAddrType == 1) {
      await getOutStoreReceiptsUser(data).then((res) => {
        if (res.data.success) {
          modules.value = res.data.data.rows
        } else {
          ElMessage({
            showClose: true,
            message: res.data.message,
            duration: 5000,
            plain: true,
            type: 'error',
          })
        }
        loadingEmp.value = false
      })
    } else {
      await storeEmpAddressPageSelect(data, newOutForm.value.receiptVo.receiptAddrType - 1).then(
        (res) => {
          if (res.data.success) {
            modules.value = res.data.data.rows
          } else {
            ElMessage({
              showClose: true,
              message: res.data.message,
              duration: 5000,
              plain: true,
              type: 'error',
            })
          }
          loadingEmp.value = false
        },
      )
    }
  }
  // 人员选择变化
  const changerelationId = (n) => {
    modules.value.map((o) => {
      if (n == o.id) {
        newOutForm.value.receiptVo.receiptName = o.userName || o.username
        newOutForm.value.receiptVo.receiptPhone = o.phone
        newOutForm.value.receiptVo.receiptAddress = o.address
        newOutForm.value.receiptVo.receiptProvince = o.province
        newOutForm.value.receiptVo.receiptCity = o.city
        newOutForm.value.receiptVo.receiptArea = o.area
        newOutForm.value.receiptVo.receiptTown = o.town
        addrsObj.value = {
          province: o.province,
          city: o.city,
          area: o.area,
          town: o.town,
        }
      }
    })
  }
  // 获取仓库列表
  const storePageSelectList = ref<Array<WarehouseOptions>>([])
  const getstorePageSelect = async (val) => {
    loadingEmp.value = true
    const data = {
      limit: 0,
      name: val,
      page: 0,
    }
    await storePageSelect(data, newOutForm.value.storeType).then((res) => {
      if (res.data.success) {
        storePageSelectList.value = res.data.data.rows
      } else {
        ElMessage({
          showClose: true,
          message: res.data.message,
          duration: 5000,
          plain: true,
          type: 'error',
        })
      }
      loadingEmp.value = false
    })
  }
  // 列表仓库变化
  const changeSeleStoreId = (row, index) => {
    commoditys.value[index].storePositionId = null
    if (!faultsStorePositionFun2(row.storeId)) {
      getstorePositionPageSelect('', row.storeId, index)
    } else {
      changeSelestorePositionIdRow(row, index)
    }
  }
  const inputValueSelech = ref('')
  const inputValueSchstorePageSelect = (val) => {
    inputValueSelech.value = val
  }
  watch(inputValueSelech, (n) => {
    getstorePageSelect(n)
  })
  const brandLoading = ref(false)
  const dataType = ref(null)
  const getGoodsDialog = ref(false)
  const multipleTableRef3 = ref<InstanceType<typeof ElTable>>()
  const orderGoodsVos3 = ref([]) //选择设备信息
  const loading2 = ref(false)
  const pagination3 = ref()
  const input = ref('')
  const brandId = ref(null) // 品牌ID
  const itemIndex = ref(null)
  const goodsTypeId = ref('') // 设备分类ID
  const goodstableData = ref([])
  const typeTotal3 = ref(0)
  const goodstotal = ref(0)
  const currentPage = ref(1)
  const pageSize = ref(15)
  const brandVal = ref()
  // 搜索框下拉数据
  const brandOptions = ref([])
  // 点击设备类型
  const onClickItem = (val) => {
    itemIndex.value = val
    goodsTypeId.value = val
    getorderGoods()
  }
  const goodsType = ref(1) //设备类型：1-成品，2-物料
  // 获取设备信息列表
  const getorderGoods = async (val = true) => {
    if (val) pagination3.value.setPage()
    const data = {
      brandId: brandId.value,
      keyword: input.value,
      limit: pagination3.value.size,
      page: pagination3.value.current,
      typeId: goodsTypeId.value,
    }
    loading2.value = true
    await getInOrOutStoreGoods(data, goodsType.value).then((res) => {
      loading2.value = false
      if (res.data.success) {
        goodstableData.value = res.data.data.rows
        typeTotal3.value = Number(res.data.data.total)
        // 重新渲染 设备信息选择
        goEditProductDialog()
      }
    })
  }
  //重新渲染
  const goEditProductDialog = async () => {
    // 点击打开 添加设备 获取已添加的渲染回显
    if (commoditys.value.length > 0) {
      orderGoodsVos3.value = JSON.parse(JSON.stringify(commoditys.value))
    }
    // // 重新渲染 设备信息选择
    orderGoodsVos3.value.map((goods) => {
      goodstableData.value.find((item) => {
        if (item.specId === goods.goodsSpecId) {
          nextTick(() => {
            multipleTableRef3.value!.toggleRowSelection(item, undefined)
          })
        }
      })
    })
  }
  // current-page 改变时触发
  const handleCurrentChange = (page: number) => {
    currentPage.value = page
    getTypeData()
  }
  // 获取设备类型
  const typeloading = ref(false)
  const getTypeData = async () => {
    typeloading.value = true
    const data = {
      limit: pageSize.value,
      name: '',
      page: currentPage.value,
    }
    await typePageSelect(data).then((res) => {
      dataType.value = res.data.data.rows
      goodstotal.value = Number(res.data.data.total)
      typeloading.value = false
    })
  }
  // 查看图片
  const dialogVisible = ref(false)
  const lookImgUrl = ref(null)
  const lookPic = (img) => {
    lookImgUrl.value = img
    dialogVisible.value = true
  }
  // 搜索品牌下拉数据输入搜索
  const searchBrandSelect = (query: string) => {
    brandVal.value = query
  }
  watch(brandVal, (n) => {
    getBrandOptions(n)
  })
  // 获取品牌下拉数据
  const getBrandOptions = async (name) => {
    const data = {
      limit: 0,
      name: name,
      page: 0,
    }
    brandLoading.value = true
    await brandPageSelect(data).then((res) => {
      brandOptions.value = res.data.data.rows
    })
    brandLoading.value = false
  }
  // 设备信息列表勾选 全选
  const selectAllgoodsinformation = (val) => {
    if (val.length > 0) {
      val.map((row) => {
        const result = orderGoodsVos3.value.some((o) => row.specId == o.goodsSpecId)
        const item = {
          image: row.image,
          storeId: null,
          storePositionId: null,
          code: row.code,
          storePositionList: [],
          stockCodeVos: [],
          stockCodeVosTemp: [],
          unit: row.unit,
          id: null,
          goodsId: row.id,
          goodsBrand: row.brand,
          goodsModel: row.model,
          goodsName: row.name,
          goodsSpecId: row.specId,
          remark: '',
          goodsSpecName: row.specName,
          price: row.price,
          goodsType: row.type,
          qty: 1,
          type: goodsType.value,
        }
        if (!result) {
          orderGoodsVos3.value.push(item)
        }
      })
    } else if (val.length == 0) {
      goodstableData.value.map((row) => {
        orderGoodsVos3.value = orderGoodsVos3.value.filter((o) => o.goodsSpecId != row.specId)
      })
    }
  }
  // 勾选 设备信息
  const handleClickgoodsinformation = (val, row) => {
    const item = {
      image: row.image,
      storeId: null,
      storePositionId: null,
      storePositionList: [],
      stockCodeVos: [],
      stockCodeVosTemp: [],
      unit: row.unit,
      code: row.code,
      id: null,
      goodsId: row.id,
      goodsBrand: row.brand,
      goodsModel: row.model,
      goodsName: row.name,
      goodsSpecId: row.specId,
      remark: '',
      goodsSpecName: row.specName,
      price: row.price,
      goodsType: row.type,
      qty: 1,
      type: goodsType.value,
    }
    const result = val.some((item) => item.specId == row.specId) //判断是否是 选中
    if (result) {
      orderGoodsVos3.value.push(item)
    } else {
      orderGoodsVos3.value = orderGoodsVos3.value.filter((o) => o.goodsSpecId != row.specId)
    }
  }
  //   设备选择弹窗
  const addGoodsList = () => {
    getGoodsDialog.value = true
    orderGoodsVos3.value = []
    new Promise(() => {
      getTypeData()
      getBrandOptions('')
      nextTick(() => {
        getorderGoods()
      })
    })
  }
  const detelePro = (index) => {
    commoditys.value = commoditys.value.filter((o, i) => i != index)
  }
  // 确定 选择的设备
  const onCommit = () => {
    // 工单序列号设备类型type：1-公司已登记设备，2-未登记设备，3-设备信息,示例值(1)
    if (commoditys.value.length > 0) {
      // 设备信息
      if (orderGoodsVos3.value.length > 0) {
        const arr = [] //旧
        const arr2 = [] //新

        orderGoodsVos3.value.filter((goods) => {
          const result = commoditys.value.some((i) => i.goodsSpecId == goods.goodsSpecId)
          if (result) {
            arr.push(...commoditys.value.filter((i) => i.goodsSpecId == goods.goodsSpecId))
          } else {
            arr2.push(goods)
          }
        })

        commoditys.value = [...arr, ...arr2]
      }
    } else {
      if (orderGoodsVos3.value.length > 0) {
        commoditys.value = orderGoodsVos3.value
      }
    }
    orderGoodsVos3.value = []
    getGoodsDialog.value = false
  }
  const onCancel = () => {
    getGoodsDialog.value = false
    orderGoodsVos3.value = []
  }
  // 判断是否启用仓位
  const faultsStorePositionFun = (id) => {
    if (id) {
      for (const obj of modules.value) {
        if (obj.id == id) {
          return !obj.enableStorePosition
        }
      }
    }
    return true
  }
  // 仓位选择输入搜索
  const valuestorePosition = ref({ val: '', id: null, index: null })
  const changeSelestorePositionId = (val, id, index = null) => {
    valuestorePosition.value.val = val
    valuestorePosition.value.id = id
    valuestorePosition.value.index = index
  }
  // 监听仓位选择输入搜索变化
  watch(
    () => valuestorePosition.value.val,
    (n) => {
      getstorePositionPageSelect(n, valuestorePosition.value.id, valuestorePosition.value.index)
    },
  )
  watch(
    () => newOutForm.value.receiptVo.relationId,
    (n) => {
      newOutForm.value.receiptVo.storePositionId = null
      storePositionList.value = []
      if (newOutForm.value.receiptVo.receiptAddrType != 1) {
        if (!faultsStorePositionFun(newOutForm.value.receiptVo.relationId)) {
          getstorePositionPageSelect('', n)
        }
      }
    },
  )
  // 列表判断是否启用仓位
  const faultsStorePositionFun2 = (id) => {
    if (id) {
      for (const obj of storePageSelectList.value) {
        if (obj.id == id) {
          return !obj.enableStorePosition
        }
      }
    }
    return true
  }
  const receiptAddrTypeChange = () => {
    getstoreEmpAddressPageSelect('')
    modules.value = []
    newOutForm.value.receiptVo.relationId = null
    addrsObj.value = {
      province: '',
      city: '',
      area: '',
      town: '',
    }
    newOutForm.value.receiptVo.receiptName = ''
    newOutForm.value.receiptVo.receiptPhone = ''
    newOutForm.value.receiptVo.receiptAddress = ''
    newOutForm.value.receiptVo.receiptProvince = ''
    newOutForm.value.receiptVo.receiptCity = ''
    newOutForm.value.receiptVo.receiptArea = ''
    newOutForm.value.receiptVo.receiptTown = ''
    addrsDom.value.clearSelectAddr()
  }

  // 仓位下拉数据
  const storePositionList = ref([])
  const getstorePositionPageSelect = async (val: string, storeId, index = null) => {
    const data = {
      limit: 0,
      name: val,
      page: 0,
    }
    if (storeId) {
      await storePositionPageSelect(data, storeId).then((res) => {
        if (res) {
          if (index || index === 0) {
            commoditys.value[index].storePositionList = res.data.data.rows
          } else {
            storePositionList.value = res.data.data.rows
          }
        }
      })
    }
  }

  //仓库下拉变化 获取设备即时库存
  const changeSelestorePositionIdRow = (row, index) => {
    if (row.storeId) {
      const data = {
        goodsId: row.goodsId, //设备ID
        goodsSpecId: row.goodsSpecId, //设备规格ID
        storeId: row.storeId, //仓库ID
        storePositionId: row.storePositionId, //仓库仓位ID，当仓库启用仓位时，此字段必传
        type: row.type, //设备类型：1-成品，2-物料
      }
      commoditys.value[index].systemStock = 0
      if (!faultsStorePositionFun2(row.storeId)) {
        data.storePositionId = row.storePositionId
      }
      getGoodsStock(data).then((res) => {
        if (res) {
          if (res.data.code == 20000) {
            if (res.data.data.row.id) {
              commoditys.value[index].price = res.data.data.row.price
            }
            commoditys.value[index].systemStock = res.data.data.row.systemStock
          }
        }
      })
    }
  }

  // 获取序列号
  const getCodeDialog = ref(false) //弹窗
  const stockCodeVosTemp = ref([]) //在库选择的选中数据
  const keywordCode = ref('')
  const paginationRef = ref()
  const totalCode = ref(0)
  const getListCode = ref([])
  const selectCodeRef = ref()
  const getStoreCodeListLoading = ref(false)
  const getInStoreCodeListData = async (val = true) => {
    if (val) paginationRef.value.setPage()
    const data = {
      goodsId: currentOperateCommodity.value.goodsId,
      goodsSpecId: currentOperateCommodity.value.goodsSpecId,
      keyword: keywordCode.value,
      limit: paginationRef.value.size,
      page: paginationRef.value.current,
      storeId: currentOperateCommodity.value.storeId,
      storePositionId: currentOperateCommodity.value.storePositionId,
      type: currentOperateCommodity.value.type,
    }
    getStoreCodeListLoading.value = true
    await getInStoreCodeList(data).then((res) => {
      if (res) {
        totalCode.value = Number(res.data.data.total)
        getListCode.value = res.data.data.rows
        // // 重新渲染 设备信息选择
        stockCodeVosTemp.value.map((goods) => {
          getListCode.value.map((item) => {
            if (item.id === goods.id) {
              nextTick(() => {
                selectCodeRef.value!.toggleRowSelection(item, undefined)
              })
            }
          })
        })
      }
    })
    getStoreCodeListLoading.value = false
  }
  // 选择删除选中序列号
  const deteleCode = (index) => {
    commoditys.value[currentOperateCommodity.value.index].stockCodeVosTemp = commoditys.value[
      currentOperateCommodity.value.index
    ].stockCodeVosTemp.filter((o, n) => n != index)
  }
  const onclickSave = async () => {
    if (!ruleFormRef.value) return
    await ruleFormRef.value.validate((valid) => {
      if (valid && submitVerify()) {
        checkDialog.value = true
      }
    })
  }
  const checkDialog = ref(false)
  // 驳回
  const rejectDialog = ref(false)
  // 驳回出库单
  const rejectLoading = ref(false)
  const onrejectOutbound = async () => {
    loading.value = true
    rejectLoading.value = true
    await rejectOutbound({ remark: newOutForm.value.reviewRemark }, route.params.id).then((res) => {
      if (res) {
        ElMessage({
          showClose: true,
          message: res.data.message,
          duration: 5000,
          plain: true,
          type: res.data.success ? 'success' : 'error',
        })
        if (res.data.success) {
          rejectDialog.value = false
          TagsViewStore.delView(route.path)
          router.push('/storage/outb')
        }
      }
      rejectLoading.value = false
    })
    loading.value = false
  }

  const ruleFormRef = ref()
  // 提交类型：1-保存，2-审核
  const agreeLoading = ref(false)
  const onSaveAudit = async (type) => {
    if (!ruleFormRef.value) return
    await ruleFormRef.value.validate((valid) => {
      if (valid && submitVerify()) {
        agreeLoading.value = true
        if (commoditys.value.length > 0) {
          newOutForm.value.outBoundMaterialVos = commoditys.value.map((o) => {
            return {
              goodsId: o.goodsId, //物料ID
              goodsSpecId: o.goodsSpecId, //物料规格ID
              id: o.id, //
              price: o.price, //物料单价
              qty: o.qty, //物料出/入库数量,示例1
              remark: o.remark, //物料出/入库备注
              stockCodeVos: o.stockCodeVos,
              storeId: o.storeId, //仓库ID
              storePositionId: o.storePositionId, //仓库仓位ID，当仓库启用仓位时，此字段必传
              type: o.type, //	物料类型：1-成品 ，2-备件
            }
          })
        }
        // 删除的入库物料ID集合
        newOutForm.value.delOutBoundMaterialIds = orderGoodsListtem.value.filter((i) => {
          const result = commoditys.value.some((o) => o.id == i.id)
          if (!result) {
            return i.id
          }
        })
        newOutForm.value.delOutBoundMaterialIds = newOutForm.value.delOutBoundMaterialIds.map(
          (o) => o.id,
        )
        saveOrCheck(newOutForm.value, type).then((res) => {
          agreeLoading.value = false
          if (res) {
            ElMessage({
              showClose: true,
              message: res.data.message,
              duration: 5000,
              plain: true,
              type: res.data.success ? 'success' : 'error',
            })
            if (res.data.success) {
              TagsViewStore.delView(route.path)
              router.push('/storage/outb')
              refresh()
            }
          }
        })
      }
    })
  }

  // 根据仓库ID获取仓库详情
  const getDetailStoreItem = async () => {
    loading.value = true
    if (route.params.id) {
      await getOutboundDetail(route.params.id).then((res) => {
        if (res) {
          if (res.data.code == 20000) {
            const temp = res.data.data.row
            newOutForm.value = {
              createTime: temp.createTime, //单据日期
              estimateTime: temp.estimateTime, //	预计出库时间
              id: temp.id, //
              delOutBoundMaterialIds: [], //删除的出库物料ID集合
              outboundNo: temp.outboundNo,
              outBoundMaterialVos: [],
              receiptVo: {
                receiptAddrType: temp.receiptAddrType, //收货地址类型：1-公司，2-部门仓库，3-工程师仓库,示例值(1)
                receiptAddress: temp.receiptAddress, //
                receiptArea: temp.receiptArea, //
                receiptCity: temp.receiptCity, //
                receiptName: temp.receiptName, //收货人姓名
                receiptPhone: temp.receiptPhone, //
                receiptProvince: temp.receiptProvince, //
                receiptTown: temp.receiptTown, //
                relationId: temp.relationId, //用户表ID/仓库ID
                storePositionId: temp.storePositionId, //仓库仓位ID，当仓库启用仓位时生效
              },
              remark: temp.remark, //单据备注
              reviewRemark: temp.reviewRemark, //	审核备注
              source: temp.source, //单据来源：1-系统单，2-工单，3-ERP单据，4-仓库移动端单据，5-第三方系统单据,示例值(1)
              storeType: temp.storeType, //仓库类型：0-内部仓库，1-部门-外部仓库，2-工程师-外部仓库
              typeId: temp.typeId, //出库类型ID
            }
            addrsObj.value = {
              province: temp.receiptProvince,
              city: temp.receiptCity,
              area: temp.receiptArea,
              town: temp.receiptTown,
            }
            getstoreEmpAddressPageSelect('')
            getstorePageSelect('')
          } else {
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'error',
              duration: 5000,
              plain: true,
            })
          }
        }
      })
    }
    loading.value = false
  }
  //设备信息
  const orderGoodsListtem = ref([]) //已经存在的设备
  const getoutStoreList = async () => {
    loading.value = true
    if (route.params.id) {
      await getOutboundMaterial(route.params.id).then((res) => {
        if (res) {
          if (res.data.code == 20000) {
            commoditys.value = res.data.data.row
            orderGoodsListtem.value = res.data.data.row
            commoditys.value = commoditys.value.map((o, index) => {
              const stockCodeVosTemp = o.stockCodeVos.map((n: { code: string; codeId: string }) => {
                return {
                  ...n,
                  goodsBrand: o.goodsBrand,
                  goodsName: o.goodsName,
                  goodsModel: o.goodsModel,
                  goodsSpecName: o.goodsSpecName,
                  store: o.store,
                  storePosition: o.storePosition,
                }
              })
              snCodeBeforeAudit.value[index] = _.cloneDeep(stockCodeVosTemp)
              getstorePositionPageSelect('', o.storeId, index)
              return { ...o, unit: o.goodsUnit, stockCodeVosTemp: stockCodeVosTemp }
            })
          } else {
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'error',
              duration: 5000,
              plain: true,
            })
          }
        }
      })
    }
    loading.value = false
  }
  // 取消
  const oncancenlPage = () => {
    ruleFormRef.value?.resetFields()
    TagsViewStore.delView(route.path)
    router.push('/storage/outb')
  }

  watch(outStoreTypeValue, (n) => {
    getoutStoreTypePageSelect(n)
  })

  watch(valuestoreEmpAddress, (n) => {
    getstoreEmpAddressPageSelect(n)
  })

  onMounted(() => {
    if (route.params.id) {
      getoutStoreList()
      getDetailStoreItem()
    } else {
      getstorePageSelect('')
    }
  })
  return {
    dateType,
    getoutStoreTypePageSelect,
    changeOutType,
    receiptAddrType,
    getstoreEmpAddressPageSelect,
    checkDialog,
    onrejectOutbound,
    source,
    status,
    outStoreType,
    typeLoading,
    storeType,
    addressValChange,
    inputValueSch,
    changerelationId,
    modules,
    storePositionList,
    receiptAddrTypeChange,
    newOutForm,
    storeListRef,
    faultsStorePositionFun,
    changeSelestorePositionId,
    getStoreCodeListLoading,
    inputValueSchstorePageSelect,
    storeTypeChange,
    addrsObj,
    rulesOutStore,
    addrsDom,
    typeloading,
    onCommit,
    onCancel,
    detelePro,
    ruleFormRef,
    storePageSelectList,
    oncancenlPage,
    loading,
    total,
    pagination,
    tableDataList,
    dialogVisible,
    lookImgUrl,
    addGoodsList,
    pagination3,
    multipleTableRef3,
    onSaveAudit,
    onclickSave,
    rejectDialog,
    itemIndex,
    getGoodsDialog,
    dataType,
    onClickItem,
    handleCurrentChange,
    currentPage,
    pageSize,
    goodstotal,
    loading2,
    brandLoading,
    lookPic,
    faultsStorePositionFun2,
    brandId,
    searchBrandSelect,
    getorderGoods,
    brandOptions,
    input,
    Search,
    goodstableData,
    selectAllgoodsinformation,
    typeTotal3,
    handleClickgoodsinformation,
    changeSeleStoreId,
    changeSelestorePositionIdRow,
    getCodeDialog,
    keywordCode,
    paginationRef,
    totalCode,
    getInStoreCodeListData,
    getListCode,
    goodsType,
    selectCodeRef,
    deteleCode,
    agreeLoading,
    rejectLoading,
    commoditys,
    currentOperateCommodity,
    selectSnCodeDialogVisible,
    onConfirmSnCode,
    handleSnCodeSelectionChange,
    handleShowSelectSnCodeDialog,
  }
}
